package com.example.api.service;

import com.example.api.entity.Category;
import com.example.api.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CategoryService {
    private final CategoryRepository categoryRepository;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public CategoryService(CategoryRepository categoryRepository) {
        this.categoryRepository = categoryRepository;
    }

    private static final String ALL_CATEGORIES_CACHE_KEY = "categories:all";
    private static final String CATEGORY_KEYWORD_CACHE_KEY_PREFIX = "categories:keyword:";
    private static final long CACHE_EXPIRATION_TIME = 10; // 缓存过期时间，单位：分钟

    // 获取所有类别
    public List<Category> getAllCategories() {
        // 尝试从 Redis 缓存中获取所有类别数据
        List<Category> cachedCategories = (List<Category>) redisTemplate.opsForValue().get(ALL_CATEGORIES_CACHE_KEY);
        if (cachedCategories != null) {
            return cachedCategories;
        }

        // 如果缓存中没有数据，从数据库中获取
        List<Category> categories = categoryRepository.findAll();

        // 将数据存入 Redis 缓存中
        redisTemplate.opsForValue().set(ALL_CATEGORIES_CACHE_KEY, categories, CACHE_EXPIRATION_TIME, TimeUnit.MINUTES);

        return categories;
    }

    // 根据关键字获取类别
    public List<Category> getCategoriesByKeyword(String keyword) {
        // 构建缓存的 key
        String cacheKey = CATEGORY_KEYWORD_CACHE_KEY_PREFIX + keyword;

        // 尝试从 Redis 缓存中获取数据
        List<Category> cachedCategories = (List<Category>) redisTemplate.opsForValue().get(cacheKey);
        if (cachedCategories != null) {
            return cachedCategories;
        }

        // 如果缓存中没有数据，从数据库中获取
        List<Category> categories = categoryRepository.findByCategoryIdContaining(keyword);

        // 将数据存入 Redis 缓存中
        redisTemplate.opsForValue().set(cacheKey, categories, CACHE_EXPIRATION_TIME, TimeUnit.MINUTES);

        return categories;
    }
}
